package yxy.game.pm2.active.command.weeklycard;

import yxy.apple.logger.Logger;
import yxy.cherry.data.bean.actweekcarreward;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.active.module.ActiveModule_周卡;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.active.module.subordinateclass.weeklycard.WeeklyTargetTask;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ActiveMessage;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.module.CurrencyHandle;

import java.util.ArrayList;
import java.util.Map;

/**
 * 周卡_目标任务 领取宝箱
 * @author Dell
 *
 */
@MessageType(proto = Command.ActWeeklyCardTargetDrawReward, classtype = ActiveMessage.ActWeeklyCardTargetDrawRewardRequest.class)
public class CMD_Active_周卡_目标任务_DrawReward extends Command<ActiveMessage.ActWeeklyCardTargetDrawRewardRequest> {

	private static final Logger logger = Logger.create(CMD_Active_周卡_目标任务_DrawReward.class);
	
	@Override
	public void execute(MessageSource messageSource, ActiveMessage.ActWeeklyCardTargetDrawRewardRequest request) throws Exception {
		String playercode = messageSource.getTag();
		ActiveMessage.ActWeeklyCardTargetDrawRewardResponse.Builder response = ActiveMessage.ActWeeklyCardTargetDrawRewardResponse.newBuilder();
		
		ActiveModule_周卡 am = ActiveModule_周卡.get(playercode,false);
		if(am == null) {
			send(messageSource, response, Result.ActNoOpen);
			return;
		}
		
		if(!am.running()) {
			send(messageSource, response, Result.ActNoOpen);
			return;
		}

		WeeklyTargetTask wtt = am.getWtt();
		if(wtt.getGetids().size() >= wtt.getUnlockids().size()) {
			send(messageSource, response, Result.ActCannotGet);
			return;
		}
		
		Map<String, actweekcarreward> awcrmap = ActDataCenter.getAllData(actweekcarreward.class, playercode);
		
		ArrayList<Integer> addids = new ArrayList<Integer>();
		ArrayList<Currency> curs = new ArrayList<Currency>();
		for(int id : wtt.getUnlockids()) {

			if(wtt.getGetids().contains(id)) {
				continue;
			}
			
			actweekcarreward data = awcrmap.get(String.valueOf(id));
			
			Currency cur = Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum());
			curs.add(cur);
			addids.add(id);
			
			PackageMessage.Item item = new CurrencyHandle().packItem(cur);
			response.addDisplay(item);
		}
		
		wtt.getGetids().addAll(addids);
		am.set();
		new CurrencyHandle().addCurrency(playercode, CCReason.活动_周卡, curs);
		
		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, ActiveMessage.ActWeeklyCardTargetDrawRewardResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}
